<script lang="ts" setup>
import { onMounted, ref } from 'vue';
import { KeyValues } from '../../utils/types';
import { FormInstance, FormItemRule } from 'element-plus';
import { nameListTypeSelect, nameListStatusSelect, createNonEmptyRule } from '../../utils';
import { apiAccessControl } from '../../api';

const props = defineProps<{
  row?: any
}>()

const emit = defineEmits(['close', 'submitted'])

const form = ref<KeyValues>({
  bizType: 0,
  type: nameListTypeSelect.BLACK,
  status: nameListStatusSelect.ENABLED
})

const formRef = ref<FormInstance>()

const rules: { [k: string]: FormItemRule } = {
  name: createNonEmptyRule('请输入规则名称'),
  address: createNonEmptyRule('请输入IP地址'),
  rejectedCode: createNonEmptyRule('请输入状态码')
}

const close = () => emit('close')

const loading = ref(false)

const onOk = async () => {
  await formRef.value.validate()
  loading.value = true
  try {
    await apiAccessControl.save(form.value)
    emit('submitted')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  const { row } = props
  if (row) {
    form.value = { ...row }
  }
})
</script>

<template>
  <ElDialog>
    <ElForm ref="formRef" label-width="6em" :model="form" :rules="rules">
      <ElFormItem label="规则名称" prop="name">
        <ElInput v-model="form.name"/>
        <ElText type="info" size="small">任意描述字符串</ElText>
      </ElFormItem>
      <ElFormItem label="名单类型">
        <ElRadioGroup v-model="form.type">
          <ElRadio v-for="_ in nameListTypeSelect.data" :key="_.value" :label="_.value">
            {{ _.label }}
          </ElRadio>
        </ElRadioGroup>
      </ElFormItem>
      <ElFormItem label="IP地址" prop="address">
        <ElInput v-model="form.address" />
        <ElText type="info" size="small">如果IP地址在白名单则优先于黑名单,多个用逗号分隔如:10.0.0.*,12.0.0.*</ElText>
      </ElFormItem>
      <template v-if="form.type === nameListTypeSelect.BLACK">
        <ElFormItem label="状态码" prop="rejectedCode">
          <ElInputNumber controls-position="right" :min="200" v-model="form.rejectedCode" />
          <ElText style="width: 100%;" type="info" size="small">拒绝时返回的HTTP状态码</ElText>
        </ElFormItem>
        <ElFormItem label="提示内容" prop="rejectedMsg">
          <ElInput type="textarea" v-model="form.rejectedMsg" />
          <ElText type="info" size="small">拒绝访问时的提示消息</ElText>
        </ElFormItem>
      </template>
      <ElFormItem label="状态" prop="status">
        <ElRadioGroup v-model="form.status">
          <ElRadio v-for="_ in nameListStatusSelect.data" :key="_.value" :label="_.value">
            {{ _.label }}
          </ElRadio>
        </ElRadioGroup>
      </ElFormItem>
    </ElForm>
    <template #footer>
      <ElButton @click="close">取消</ElButton>
      <ElButton type="primary" :loading="loading" @click="onOk">确定</ElButton>
    </template>
  </ElDialog>
</template>
